﻿namespace Leetcode.N0068;
public class Solution
{
    public IList<string> FullJustify(string[] words, int maxWidth)
    {

        var lineWidth = words[0].Length;
        int from = 0;
        var ans = new List<string>();
        for (int i = 1; i < words.Length; i++)
        {
            if (lineWidth + 1 + words[i].Length > maxWidth)
            {
                ans.Add(this.FullJustify(words, from, i - 1, maxWidth - lineWidth));
                lineWidth = words[i].Length;
                from = i;
            }
            else
            {
                lineWidth += 1 + words[i].Length;
            }
        }

        ans.Add(this.FullJustifyEndLine(words, from, maxWidth));
        return ans;
    }

    private string FullJustify(string[] words, int from, int to, int fillSpace)
    {
        var wordCount = to - from + 1;
        var spaceCount = (wordCount == 1 ? 0 : fillSpace / (wordCount - 1)) + 1;
        var spaceMode = wordCount == 1 ? 0 : fillSpace % (wordCount - 1);
        var stringBuilder = new System.Text.StringBuilder();

        for (int i = from; i < to; i++)
        {
            stringBuilder.Append(words[i]);
            stringBuilder.Append(new string(' ', spaceCount));
            if (spaceMode > 0)
            {
                stringBuilder.Append(' ');
                spaceMode--;
            }
        }
        stringBuilder.Append(words[to]);
        if (wordCount == 1 && spaceCount > 0)
        {
            stringBuilder.Append(new string(' ', fillSpace));
        }
        return stringBuilder.ToString();
    }

    private string FullJustifyEndLine(string[] words, int from, int maxWidth)
    {

        var stringBuilder = new System.Text.StringBuilder();
        for (int i = from; i < words.Length - 1; i++)
        {
            stringBuilder.Append(words[i]);
            stringBuilder.Append(' ');
        }

        stringBuilder.Append(words[words.Length - 1]);

        if (stringBuilder.Length < maxWidth)
        {
            stringBuilder.Append(new string(' ', maxWidth - stringBuilder.Length));
        }
        return stringBuilder.ToString();
    }
}